app.controller('setupIdeaPageCtrl',function($scope,$state,PopupService,$stateParams,$http,$myconfig,$timeout,$mydialog,$ionicConfig,$cordovaCamera,$ionicLoading){

    $scope.userMes = JSON.parse(localStorage.getItem('user'));
    //向服务器请求数据详情

    $scope.headimgurl = [];

    $scope.setIdea = function(name){
        $http.post($myconfig.api.base_host + '/feedback/add_feedback' , {
            	"user_id":$scope.userMes.id,
                "content":$scope.userMes.idea,
                "mobile":$scope.userMes.mobile,
                "picture":$scope.headimgurl
        }).then(function(res){
            if(res.data.success){
                $scope.success_text = res.data.data;
                $mydialog.success($scope);
                $scope.headimgurl = [];
                $state.go('app.setup');
            }else{
                $scope.err = res.data.data;
                $mydialog.fail($scope);
            }
        });
    };



    //新增反馈图片
       //选择用户头像
    $scope.openCam = function() {
        PopupService.CameraS($scope);
    };

    //执行拍照功能
    $scope.camPlay = function(cam) {
        document.addEventListener("deviceready", function() {

            //照片相机参数
            var options = {
                quality: 80, //保存的图像质量，范围为0 - 100
                destinationType: Camera.DestinationType.DATA_URL, //	返回值格式
                sourceType: cam, //设置图片来源
                //  Camera.PictureSourceType.CAMERA,
                MediaType: 0,
                allowEdit: true, //	选择图片前是否允许编辑
                encodingType: Camera.EncodingType.JPEG, //	JPEG = 0, PNG = 1
                targetWidth: 100, //缩放图像的宽度（像素）
                targetHeight: 100, //缩放图像的高度（像素）
                popoverOptions: CameraPopoverOptions, //	iOS,iPad弹出位置
                saveToPhotoAlbum: false, //是否保存到相册
                correctOrientation: true //设置摄像机拍摄的图像是否为正确的方向
            };

            $cordovaCamera.getPicture(options).then(function(imageData) {
                //成功后回调函数，将图片预览至手机，并保存64位地址至本地
                var image = document.getElementById('myIdeaImage');
                console.log(image);
                image.src = "data:image/jpeg;base64," + imageData;
                // $scope.headimgurl = image.src;
                // console.log( $scope.headimgurl);
                putb64(image.src, function() {
                        $ionicLoading.hide();
                    });
                    // Setup the loader
                    //  console.log('执行加载动作')
                $ionicLoading.show({
                    content: '图片上传中，请稍后。。。',
                    animation: 'fade-in',
                    showBackdrop: false,
                    maxWidth: 200,
                    showDelay: 0
                });
            }, function(err) {
                // error
            });

        }, false);
    };




    /*通过base64编码字符流计算文件流大小函数*/
    function fileSize(str) {
        var fileSize;
        if (str.indexOf('=') > 0) {
            var indexOf = str.indexOf('=');
            str = str.substring(0, indexOf); //把末尾的’=‘号去掉
        }

        fileSize = parseInt(str.length - (str.length / 8) * 2);
        return fileSize;
    }
    //七牛64位图片上传
    function putb64(base64, callback) {
        $http.get($myconfig.api.base_host + '/qn/token/header')
            .then(function(res) {
                // console.log(res);
                var pic = base64.split(',')[1];
                var url = 'http://up.qiniu.com/putb64/' + fileSize(pic) + '/key/' + res.data.key;
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function() {
                        if (xhr.readyState == 4) {
                            // console.log('关闭加载动作')
                            callback(JSON.parse(xhr.responseText)); //回调返回的数据
                            console.log(JSON.parse(xhr.response).key);
                            $scope.headimgurl.push(JSON.parse(xhr.response).key);
                        }

                    }
                    // console.log(pic);
                xhr.open('POST', url, true);
                xhr.setRequestHeader('Content-Type', 'application/octet-stream');
                xhr.setRequestHeader('Authorization', 'UpToken ' + res.data.token);
                xhr.send(pic);
            });
    }






    $scope.$on('$ionicView.enter', function(){

        $ionicConfig.views.swipeBackEnabled(false);

    });

});
